class Solution {
public:
    string reverseWords(string s) {
        auto f = s.end();
        auto l = s.end();
        while (f != s.begin())
        {
            if (*f != ' ')
            {
                f--;
                continue;
            }
            if (*f == ' ' && *(f - 1) != ' ')
            {
                std::reverse(f + 1, l);
                l = f;
                f--;
            }
            else
            {
                f--;
                int ll = l - f;
                s.erase(f + 1);
                l = f + ll - 1;
            }
        }
        if (*f == ' ')
        {
            f++;
            int ll1 = l - f;
            s.erase(f - 1);
            f = s.begin();
            l = f + ll1;
        }
        std::reverse(f, l);
        if (*(s.end() - 1) == ' ')
        {
            s.pop_back();
        }
        std::reverse(s.begin(), s.end());
        return s;
    }
};